package org.ehe.erp.controller.purchase;

import cn.dev33.satoken.annotation.SaCheckPermission;
import org.ehe.business.monitor.MonitorMethod;
import org.ehe.business.overdue.extract.PurcharOrderDataExtractor;
import org.ehe.business.overdue.extract.QualityDataExtractor;
import org.ehe.business.timeout.contants.BizTypeConstant;
import org.ehe.common.core.BaseController;
import org.ehe.common.core.domain.R;
import org.ehe.common.core.utils.MapstructUtils;
import org.ehe.common.core.utils.object.BeanUtils;
import org.ehe.common.core.validate.AddGroup;
import org.ehe.common.core.validate.EditGroup;
import org.ehe.common.excel.utils.ExcelUtil;
import org.ehe.common.idempotent.annotation.RepeatSubmit;
import org.ehe.common.log.annotation.Log;
import org.ehe.common.log.enums.BusinessType;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.ehe.erp.domain.purchase.ErpPurchaseOrder;
import org.ehe.erp.domain.purchase.ErpPurchaseOrderItem;
import org.ehe.erp.domain.purchase.bo.ErpPurchaseOrderBo;
import org.ehe.erp.domain.purchase.vo.ErpPurchaseOrderItemVo;
import org.ehe.erp.domain.purchase.vo.ErpPurchaseOrderVo;
import org.ehe.erp.domain.quality.ErpQualityTask;
import org.ehe.erp.domain.quality.dto.QualityFeedbackQueryDto;
import org.ehe.erp.domain.quality.dto.QualityRecordQueryDto;
import org.ehe.erp.domain.quality.vo.ErpQualityFeedbackVo;
import org.ehe.erp.domain.quality.vo.ErpQualityRecordVo;
import org.ehe.erp.domain.quality.vo.ErpQualityTaskVo;
import org.ehe.erp.service.purchase.IErpPurchaseOrderService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.ehe.erp.service.quality.ErpQualityFeedbackService;
import org.ehe.erp.service.quality.ErpQualityRecordService;
import org.ehe.erp.service.quality.ErpQualityTaskService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 采购订单
 *
 * @author zhangenen
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/erp/purchaseOrder")
public class ErpPurchaseOrderController extends BaseController {

    private final IErpPurchaseOrderService erpPurchaseOrderService;
    private final ErpQualityTaskService qualityTaskService;
    private final ErpQualityRecordService qualityRecordService;
    private final ErpQualityFeedbackService qualityFeedbackService;

    /**
     * 查询采购订单列表
     */
    @SaCheckPermission("erp:purchaseOrder:list")
    @GetMapping("/list")
    public TableDataInfo<ErpPurchaseOrderVo> list(ErpPurchaseOrderBo bo, PageQuery pageQuery) {
        return erpPurchaseOrderService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出采购订单列表
     */
    @SaCheckPermission("erp:purchaseOrder:export")
    @Log(title = "采购订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(ErpPurchaseOrderBo bo, HttpServletResponse response) {
        List<ErpPurchaseOrderVo> list = erpPurchaseOrderService.queryList(bo);
        //TODO 导出字段补全，待补充
        ExcelUtil.exportExcel(list, "采购订单", ErpPurchaseOrderVo.class, response);
    }

    /**
     * 导入数据
     * TODO 导入功能未作用，请自行实现
     * @param file 导入文件
     */
//    @Log(title = "测试单表", businessType = BusinessType.IMPORT)
//    @SaCheckPermission("demo:demo:import")
//    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
//    public R<Void> importData(@RequestPart("file") MultipartFile file) throws Exception {
//        ExcelResult<TestDemoImportVo> excelResult = ExcelUtil.importExcel(file.getInputStream(), TestDemoImportVo.class, true);
//        List<TestDemo> list = MapstructUtils.convert(excelResult.getList(), TestDemo.class);
//        testDemoService.saveBatch(list);
//        return R.ok(excelResult.getAnalysis());
//    }
    /**
     * 获取采购订单详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("erp:purchaseOrder:query")
    @GetMapping("/detail/{id}")
    public R<ErpPurchaseOrderVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        ErpPurchaseOrderVo erpPurchaseOrder = erpPurchaseOrderService.queryById(id);

        if (erpPurchaseOrder== null){
            return R.fail();
        }
        List<ErpPurchaseOrderItemVo> erpPurchaseOrderItems = erpPurchaseOrderService.queryItemsByOrderNo(erpPurchaseOrder.getNo());
        erpPurchaseOrder.setItems(erpPurchaseOrderItems);

        //质检信息
        ErpQualityTaskVo vo = qualityTaskService.getByOrderNo(erpPurchaseOrder.getNo());
        if(Objects.nonNull(vo)){
            QualityRecordQueryDto dto = new QualityRecordQueryDto();
            dto.setTaskId(vo.getId());
            List<ErpQualityRecordVo> recordVos = qualityRecordService.queryList(dto);
            erpPurchaseOrder.setRecordVos(recordVos);

            QualityFeedbackQueryDto feedbackQueryDto = new QualityFeedbackQueryDto();
            feedbackQueryDto.setTaskId(vo.getId());
            List<ErpQualityFeedbackVo> erpQualityFeedbackVos = qualityFeedbackService.queryList(feedbackQueryDto);
            erpPurchaseOrder.setFeedbackVos(erpQualityFeedbackVos);
        }

        return R.ok(erpPurchaseOrder);
    }

    /**
     * 获取采购订单详细信息
     *
     * @param no 主键
     */
    @SaCheckPermission("erp:purchaseOrder:query")
    @GetMapping("/detailByNo/{no}")
    public R<ErpPurchaseOrderVo> getInfoByOrderNo(@NotNull(message = "采购单号不能为空")
                                         @PathVariable String no) {
        ErpPurchaseOrder erpPurchaseOrder = erpPurchaseOrderService.queryByOrderNo(no);
        if (erpPurchaseOrder== null){
            return R.fail("未找到相关采购订单！");
        }
        ErpPurchaseOrderVo erpPurchaseOrderVo = MapstructUtils.convert(erpPurchaseOrder, ErpPurchaseOrderVo.class);
        List<ErpPurchaseOrderItemVo> erpPurchaseOrderItems = erpPurchaseOrderService.queryItemsByOrderNo(erpPurchaseOrder.getNo());
        erpPurchaseOrderVo.setItems(erpPurchaseOrderItems);
        return R.ok(erpPurchaseOrderVo);
    }

    /**
     * 新增采购订单
     */
    @MonitorMethod(bizType = "purchaseOrderOverdue", extractor = PurcharOrderDataExtractor.class)
    @SaCheckPermission("erp:purchaseOrder:add")
    @Log(title = "新增采购订单", linkType = "purchaseOrder", businessType = BusinessType.INSERT, nameField = "name")
    @RepeatSubmit()
    @PostMapping("/create")
    public R<ErpPurchaseOrder> add(@Validated(AddGroup.class) @RequestBody ErpPurchaseOrderBo bo) {
        ErpPurchaseOrder order = erpPurchaseOrderService.insertByBo(bo);
        return R.ok("采购订单新增成功",order);
    }

    /**
     * 修改采购订单
     */
    //@MonitorMethod(bizType = "purchaseOrderOverdue", extractor = PurcharOrderDataExtractor.class)
    @SaCheckPermission("erp:purchaseOrder:edit")
    @Log(title = "修改采购订单", linkType = "purchaseOrder", businessType = BusinessType.UPDATE, nameField = "name")
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody ErpPurchaseOrderBo bo) {
        return toAjax(erpPurchaseOrderService.updateByBo(bo));
    }

    /**
     * 修改采购订单附件
     */
    @SaCheckPermission("erp:purchaseOrder:edit")
    @Log(title = "修改采购订单附件", linkType = "purchaseOrder", businessType = BusinessType.UPDATE, nameField = "name")
    @RepeatSubmit()
    @PostMapping("/uploadPurchaseOrderFiles")
    public R<Void> uploadPurchaseOrderFiles(@Validated(EditGroup.class) @RequestBody ErpPurchaseOrderBo bo) {
        return toAjax(erpPurchaseOrderService.updateUploadFiles(bo));
    }


    /**
     * 提交采购订单
     */
    @MonitorMethod(bizType = "purchaseOrderOverdue", extractor = PurcharOrderDataExtractor.class)
    @SaCheckPermission("erp:purchaseOrder:submit")
    @Log(title = "响应采购订单", linkType = "purchaseOrder", businessType = BusinessType.UPDATE, nameField = "name")
    @RepeatSubmit()
    @PostMapping("/respondOrder/{id}/{days}")
    public R<ErpPurchaseOrder> respondOrder(@PathVariable("id") Long id,@PathVariable("days") Integer days) {
        return R.ok(erpPurchaseOrderService.respondOrder(id,days));
    }


    /**
     * 提交响应时间
     */
    @MonitorMethod(bizType = "purchaseOrderOverdue", extractor = PurcharOrderDataExtractor.class)
    @SaCheckPermission("erp:purchaseOrder:submit")
    @Log(title = "提交采购订单响应时间", linkType = "purchaseOrder", businessType = BusinessType.UPDATE, nameField = "name")
    @RepeatSubmit()
    @PostMapping("/submitDays/{id}/{days}")
    public R<ErpPurchaseOrder> submitDays(@PathVariable("id") Long id,@PathVariable("days") Integer days) {
        return R.ok(erpPurchaseOrderService.submitDays(id,days));
    }
    /**
     * 删除采购订单
     * @param ids 主键串
     */
    @SaCheckPermission("erp:purchaseOrder:remove")
    @Log(title = "采购子订单删除", linkType = "purchaseOrder", businessType = BusinessType.DELETE, idField = "id", nameField = "name")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(erpPurchaseOrderService.deleteWithValidByIds(List.of(ids), true));
    }


    /**
     * 更新采购订单的状态
     * @param id 主键串
     */
    @SaCheckPermission("erp:purchaseOrder:check")
    @Log(title = "采购订单", businessType = BusinessType.OTHER)
    @RepeatSubmit()
    @PutMapping("/update-status")
    public R<Void> updatePurchaseOrderStatus(@RequestParam("id") String id,
                                             @RequestParam("status") Integer status) {
        return toAjax(erpPurchaseOrderService.updatePurchaseOrderStatus(id, status));
    }

    /**
     * 根据不同供应商将同一个BOM下的信息
     */
    @SaCheckPermission("erp:purchaseOrder:childrenOrder")
    @Log(title = "采购子订单", linkType = "purchaseOrder", businessType = BusinessType.INSERT, idField = "id", nameField = "name")
    @RepeatSubmit()
    @PostMapping("/createChildOrder/{id}")
    public R<ErpPurchaseOrderVo> createChildOrderByBomIdAndSupplierId(@PathVariable("id") Long id){
        return R.ok(erpPurchaseOrderService.createChildOrderBySupplierId(id));
    }


    /**
     * 审核通过
     */
    @MonitorMethod(bizType = BizTypeConstant.PURCHASEORDER+"Overdue", extractor = PurcharOrderDataExtractor.class)
    @Log(title = "采购订单审批-通过", linkType = "quality", businessType = BusinessType.UPDATE, idField = "name", nameField = "name")
    @PostMapping("/approve/{orderId}")
    public R<ErpPurchaseOrder> approveTask(@PathVariable Long orderId) {
        try {
            ErpPurchaseOrder order = erpPurchaseOrderService.approveOrder(orderId);
            return R.ok("审核通过成功",order);
        } catch (Exception e) {
            return R.fail("审核通过失败: " + e.getMessage());
        }
    }

    /**
     * 审核拒绝
     */
    @MonitorMethod(bizType = BizTypeConstant.PURCHASEORDER+"Overdue", extractor = PurcharOrderDataExtractor.class)
    @Log(title = "采购订单务审批-驳回", linkType = "quality", businessType = BusinessType.REJECT, idField = "name", nameField = "name")
    @PostMapping("/reject/{orderId}")
    public R<ErpPurchaseOrder> rejectTask(@PathVariable Long orderId) {
        try {
            ErpPurchaseOrder order = erpPurchaseOrderService.rejectOrder(orderId);
            return R.ok("审核拒绝成功，已启动超期监控",order);
        } catch (Exception e) {
            return R.fail("审核拒绝失败: " + e.getMessage());
        }
    }
}
